import { Injectable } from '@nestjs/common';
import {
  getCurrentTime,
  generateUniqueSixDigitNumber,
  beanCopy,
  formatTime,
  checkEmailOrPhone,
  beanCopyArray,
} from 'src/utils';
import { Response } from 'src/utils/response';
import { UserRepository } from './user.repository';
import { USER_PERMISSION_MAP_REVERSE } from 'src/common/const';
import {
  DetailsResponse,
  UpdateDetailsParam,
  UpdateDetailsResponse,
  QueryUsersResponse,
} from './user.interface';
import { UserRegisterDTO } from './dto/user-register.dto';
import { UserVO } from './vo/user.vo';

@Injectable()
export class UserService {
  constructor(private readonly userRepository: UserRepository) {}

  // 登陆
  async loginService(params: UserRegisterDTO) {
    if (!params.account || !params.password) {
      return Response.error({ message: '缺少账号或密码' });
    }
    const user = await this.userRepository.loginRepository(params.account);
    if (!user) {
      // 没有该账号信息
      return Response.error({ message: '该账号未注册' });
    }
    // 验证密码是否正确
    if (user.password !== params.password) {
      return Response.error({ message: '密码错误' });
    }
    const vo = new UserVO();
    const userResult = beanCopy(vo, user);
    formatTime(userResult, ['createdAt', 'updatedAt']);
    return Response.success({
      message: '登录成功',
      data: userResult,
    });
  }

  // 注册
  async registerService(params: UserRegisterDTO) {
    if (!params.account || !params.password) {
      return Response.error({ message: '缺少账号或密码' });
    }
    // 查询是否有重复账号
    const isExist = await this.userRepository.queryAccountRepository(
      params.account,
    );
    if (isExist) {
      return Response.error({ message: '该账号已存在' });
    }
    // 判断用户输入的账号是手机号还是邮箱
    const check = checkEmailOrPhone(params.account);
    // 配置用户基础账号信息
    const _userInfo: any = {
      account: params.account,
      phone: check === 'telephone' ? params.account : '',
      email: check === 'email' ? params.account : '',
      password: params.password,
      permission: USER_PERMISSION_MAP_REVERSE.user,
      // TODO: 这里需要获取到用户的ip
      location: '',
      address: params.address || '',
      // 生成用户默认昵称
      nickName: `用户${generateUniqueSixDigitNumber()}`,
      // 设置默认头像
      avatarUrl: 'http://file.zyhccflame.top/1748762213118-a4.jpeg',
      avatar: '1',
      cover: 'http://file.zyhccflame.top/1748762635460-a.webp',
      state: '1',
      gender: 'unknown',
      tags: '',
    };
    const result = await this.userRepository.registerRepository(_userInfo);
    if (!result) {
      return Response.error({ message: '注册失败' });
    }
    const vo = new UserVO();
    const userResult = beanCopy(vo, result);
    formatTime(userResult, ['createdAt', 'updatedAt']);
    return Response.success({ data: userResult });
  }

  // 查询用户列表
  async queryUsersService(): QueryUsersResponse {
    try {
      const result = await this.userRepository.queryUsersRepository();
      const vo = new UserVO();
      const userResult = beanCopyArray(vo, result);
      userResult.forEach((u: UserVO) => {
        formatTime(u, ['createdAt', 'updatedAt']);
      });
      return Response.success({ data: userResult });
    } catch (err) {
      return Response.error({ message: err.message });
    }
  }

  // 查询用户详情
  async queryDetailsService(params: { id: number }): DetailsResponse {
    if (!params.id) {
      return Response.error({ message: '未传递用户id' });
    }
    const result = await this.userRepository.queryDetailsRepository(params.id);
    if (!result) {
      return Response.error({ message: '该用户不存在' });
    }
    const vo = new UserVO();
    const userResult = beanCopy(vo, result);
    formatTime(userResult, ['createdAt', 'updatedAt']);
    return Response.success({ data: userResult });
  }

  // 删除用户
  async deleteUserService(params: { id: number }) {
    if (!params.id) {
      return Response.error({ message: '未传递用户id' });
    }
    const result = await this.userRepository.deleteUserRepository(params.id);
    if (result.affected !== 1) {
      return Response.error({ message: '删除失败' });
    }
    return Response.success({ message: '删除成功' });
  }

  // 注销用户
  async logoutService(params: { id: number }) {
    if (!params.id) {
      return Response.error({ message: '未传递用户id' });
    }
    const result = await this.userRepository.logoutRepository(params.id);
    if (result.affected !== 1) {
      return Response.error({ message: '注销失败' });
    }
    return Response.success({ message: '注销成功' });
  }

  // 修改用户信息
  async updateDetailsService(
    params: UpdateDetailsParam,
  ): UpdateDetailsResponse {
    if (!params.id) {
      return Response.error({ message: '缺少用户id' });
    }
    const updateInfo: any = {
      ...params,
      updatedAt: getCurrentTime('YYYY-MM-DD HH:mm:ss'),
    };
    const result = await this.userRepository.updateUserInfoRepository(
      params.id,
      updateInfo,
    );
    if (result.affected !== 1) {
      return Response.error({ message: '修改失败' });
    }
    return Response.success({ message: '修改成功' });
  }
}
